import { useState } from 'react'
import { Collapse, CollapseProps, Button } from 'antd'
import { getComponentById, useComponentStore } from "../../../editor/stores/components"
import { ComponentEvent as ComponentEventType, useComponentConfigStore } from "../../../editor/stores/component-config"
import { ActionModal, ActionConfig } from '../ActionModal'
import { DeleteOutlined, EditOutlined } from '@ant-design/icons';

export function ComponentEvent() {
    const { componentConfigs } = useComponentConfigStore()
    const { components, curComponent, updateComponentProps } = useComponentStore()
    const [ visbleActionModel, setVisibleActionModel ] = useState(false)
    const [ curAction, setCurAction ] = useState<ActionConfig>() // 存放编辑时操作的 action
    const [ curActionIndex, setCurActionIndex ] = useState<number>() // 存放编辑时操作的 action index
    const [ curEvent, setCurEvent ] = useState<ComponentEventType>() // 存放当前操作的 event

    const [resetKey, setResetKey] = useState(0) // 用于重置 Modal 组件，防止新增动作时，编辑动作的值被保留

    if (!curComponent) return null;

    // curEvent: { name: "onClick", label: "点击事件" }
    // config: { type: "showLink", url: "xxx" } || { type: "showModal", config: { title: "xxx", text: "xxx" } }
    // return {onclick: { actions: [{type: "showLink", xxx}, {type: "showMessage", config}] }}
    function handleModalOk(config?: ActionConfig){
        if (!config || !curEvent || !curComponent) return 

        // 有 curAction 就是编辑，没有才是新增
        if (curAction) {
            // 编辑：替换当前 action
            updateComponentProps(curComponent.id, {
                [curEvent.name]: {
                    actions: curComponent.props[curEvent.name]?.actions.map((action, index) => {
                        return index === curActionIndex ? config : action
                    })
                }
            })
        } else {
            // 新增：往当前 actions 后面追加
            updateComponentProps(curComponent.id, {
                [curEvent.name]: {
                    actions: [
                        ...curComponent.props[curEvent.name]?.actions || [],
                        config
                    ]
                }
            })
        }

        // 清空，防止后续无法进入新增逻辑
        setCurAction(undefined)
        setCurActionIndex(undefined)

        setVisibleActionModel(false)
    }

    function handleModalCancel(){
        if (curAction) setCurAction(undefined)
        setVisibleActionModel(false)
    }

    // 删除动作
    function deleteAction(event: ComponentEventType, index: number){
        if (!curComponent) return 

        updateComponentProps(curComponent.id, {
            [event.name]: {
                actions: curComponent.props[event.name]?.actions?.filter((_, i) => i !== index) || []
            }
        })
    }

    // 编辑动作
    function editAction(event: ComponentEventType, action: ActionConfig, index: number){
        if (!curComponent) return

        setCurEvent(event) // 选择的事件
        setCurAction(action) // 当前事件的动作
        setCurActionIndex(index) // 该动作是当前事件的第几个

        setVisibleActionModel(true)
    }


    // 根据component-config组件配置，渲染表单
    const items:CollapseProps['items'] = (componentConfigs[curComponent.name].events || []).map((eventConfig) => ({
        key: eventConfig.name,
        label: (
            <div className='flex justify-between leading-[30px]'>
                <div>{eventConfig.label}</div>
                <Button type="primary" onClick={(e) => {
                    e.stopPropagation();
                    setResetKey((prevKey) => prevKey + 1) // 重置 Modal 组件，每次打开都是新组件，避免被编辑影响到
                    setVisibleActionModel(true)
                    setCurEvent(eventConfig)
                }}>添加动作</Button>
            </div>
        ),
        children: (
            <div>
                {
                    curComponent.props[eventConfig.name]?.actions?.map((action: ActionConfig, index) => {
                        return <div key={index}>
                                {
                                    action.type === 'goToLink' && (
                                        <div className='relative border border-[#aaa] m-[10px] p-[10px]'>
                                            <div className='text-blue-700'>跳转链接</div>
                                            <div>{action.url}</div>
                                            <div style={{ position: 'absolute', top: 10, right: 30, cursor: 'pointer' }}
                                                onClick={() => editAction(eventConfig, action, index)}
                                                >
                                                <EditOutlined />
                                            </div>
                                            <div 
                                                style={{position: 'absolute',top: 10, right: 10,cursor: 'pointer'}}
                                                onClick={() => deleteAction(eventConfig, index)}
                                                >
                                                <DeleteOutlined />
                                            </div>
                                        </div>
                                    )
                                }
                                {
                                    action.type === 'showMessage' && (
                                        <div className='relative  border border-[#aaa] m-[10px] p-[10px]'>
                                            <div className='text-blue-700'>消息弹框</div>
                                            <div>{action.config.type}</div>
                                            <div>{action.config.text}</div>
                                            <div style={{ position: 'absolute', top: 10, right: 30, cursor: 'pointer' }}
                                                onClick={() => editAction(eventConfig, action, index)}
                                                >
                                                <EditOutlined />
                                            </div>
                                            <div 
                                                style={{position: 'absolute',top: 10,right: 10,cursor: 'pointer'}}
                                                onClick={() => deleteAction(eventConfig, index)}
                                                >
                                                    <DeleteOutlined />
                                            </div>
                                        </div>
                                    )
                                }
                                {
                                    action.type === 'customJs' && (
                                        <div className='relative border border-[#aaa] m-[10px] p-[10px]'>
                                            <div className='text-blue-700'>自定义 JS</div>
                                            <div>{action.code}</div>
                                            <div style={{ position: 'absolute', top: 10, right: 30, cursor: 'pointer' }}
                                                onClick={() => editAction(eventConfig, action, index)}
                                                >
                                                <EditOutlined />
                                            </div>
                                            <div 
                                                style={{position: 'absolute',top: 10,right: 10,cursor: 'pointer'}}
                                                onClick={() => deleteAction(eventConfig, index)}
                                                >
                                                    <DeleteOutlined />
                                            </div>
                                        </div>
                                    )
                                }
                                {
                                    action.type === 'componentMethod' && (
                                        <div className='relative border border-[#aaa] m-[10px] p-[10px]'>
                                            <div className='text-blue-700'>组件方法</div>
                                            <div>{getComponentById(action.config.componentId, components)?.desc}</div>
                                            <div>{action.config.componentId}</div>
                                            <div>{action.config.method}</div>
                                            <div style={{ position: 'absolute', top: 10, right: 30, cursor: 'pointer' }}
                                                onClick={() => editAction(eventConfig, action, index)}
                                                >
                                                <EditOutlined />
                                            </div>
                                            <div 
                                                style={{position: 'absolute',top: 10,right: 10,cursor: 'pointer'}}
                                                onClick={() => deleteAction(eventConfig, index)}
                                                >
                                                    <DeleteOutlined />
                                            </div>
                                        </div>
                                    )
                                }
                        </div>
                    })
                }
            </div>
        )
    }))
    return (
        <div className="px-[10px]">
            {/* 折叠卡片 */}
            <Collapse 
                defaultActiveKey={componentConfigs[curComponent.name].events?.map((item) => item.name)}
                className='mb-[10px]' 
                items={items}
            />
            {/* 动作弹窗 */}
            <ActionModal 
                key={resetKey}
                visible={visbleActionModel} 
                action={curAction}
                handleOk={handleModalOk} 
                handleCancel={handleModalCancel}    
            />
        </div>
    )
}